package com.levy.jituan;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;

public class ParseMain {

    public static void main(String[] args) throws IOException {
        String logFile = "G:\\经纬度\\zulin\\customer4.log";
        String saveFile = "G:\\经纬度\\zulin\\customer4_covenrt.log";
        int threadCount = 15;
        DataQueue allEnpQueue = getAllEnpQueue(logFile, saveFile);
        System.out.println("数据读取完成: " + allEnpQueue);
        if (allEnpQueue.getQueueSize() == 0) {
            return;
        }
        taskBegin(allEnpQueue, saveFile, threadCount);


    }

    public static void splitBegin() throws IOException {
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        long startTime = System.currentTimeMillis();
        splitFile("G:\\经纬度\\zulin\\customer.log", 4);
        long endTime = System.currentTimeMillis();
        System.out.println("耗费时间： " + (endTime - startTime) + " ms");
        scanner.nextLine();
    }

    public static void splitFile(String filePath, int fileCount) throws IOException {
        FileInputStream fis = new FileInputStream(filePath);
        FileChannel inputChannel = fis.getChannel();
        final long fileSize = inputChannel.size();
        long average = fileSize / fileCount;//平均值
        long bufferSize = 200; //缓存块大小，自行调整
        ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.valueOf(bufferSize + "")); // 申请一个缓存区
        long startPosition = 0; //子文件开始位置
        long endPosition = average < bufferSize ? 0 : average - bufferSize;//子文件结束位置
        for (int i = 0; i < fileCount; i++) {
            if (i + 1 != fileCount) {
                int read = inputChannel.read(byteBuffer, endPosition);// 读取数据
                readW:
                while (read != -1) {
                    byteBuffer.flip();//切换读模式
                    byte[] array = byteBuffer.array();
                    for (int j = 0; j < array.length; j++) {
                        byte b = array[j];
                        if (b == 10 || b == 13) { //判断\n\r
                            endPosition += j;
                            break readW;
                        }
                    }
                    endPosition += bufferSize;
                    byteBuffer.clear(); //重置缓存块指针
                    read = inputChannel.read(byteBuffer, endPosition);
                }
            } else {
                endPosition = fileSize; //最后一个文件直接指向文件末尾
            }

            FileOutputStream fos = new FileOutputStream(filePath + (i + 1));
            FileChannel outputChannel = fos.getChannel();
            inputChannel.transferTo(startPosition, endPosition - startPosition, outputChannel);//通道传输文件数据
            outputChannel.close();
            fos.close();
            startPosition = endPosition + 1;
            endPosition += average;
        }
        inputChannel.close();
        fis.close();

    }

    private static DataQueue getAllEnpQueue(String logFile, String saveFile) {
        Queue<Company> queue = new ArrayDeque();

//        List<String> list = FileUtil.readLines(new File(logFile), CharsetUtil.GBK);
//        List<Company> isOverList = new ArrayList<>();
//        if (FileUtil.exist(saveFile)) {
//            List<String> strings = FileUtil.readUtf8Lines(saveFile);
//            for (String s : strings) {
//                if (StrUtil.isNotBlank(s)) {
//                    try {
//                        Company company = JSON.parseObject(s, Company.class);
//                        isOverList.add(company);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        System.out.println(s);
//
//                    }
//
//                }
//            }
//        }
//
//        List<String> positionList = new ArrayList<>();
//        list.forEach(s -> {
//            StringBuilder sb = new StringBuilder();
//            if (StrUtil.isNotBlank(s)) {
//                String[] split = s.split("\\|");
//                if (split.length > 4) {
//                    if (isOverList.size() > 0) {
//                        for (Company c : isOverList) {
//                            if (c.getGroupId().contains(split[0])) {
//                                return;
//                            }
//                        }
//                    }
//                    sb.append(StrUtil.isNotBlank(split[0])?split[0].replaceAll("\"","").trim():"").append("|");
//                    sb.append(split[1]).append("|");
//                    sb.append(split[2]).append("|");
//                    if (StrUtil.isNotBlank(split[4])) {
//                        String position = split[4].replaceAll("\\/", "")
//                                .replaceAll("\\\\", "、")
//                                .replaceAll("广东省", "")
//                                .replaceAll("#GPON资源到位#", "")
//                                .replaceAll("#楼宇地址#", "")
//                                .replaceAll("#", "")
//                                .replaceAll("\r\n", "")
//                                .replaceAll(" ", "")
//                                .replaceAll("\"", "")
//                                .trim();
//                        sb.append(position).append("|");
//                        int cityIndex = position.indexOf("市");
//                        if (cityIndex > 1) {
//                            String city = position.substring(cityIndex - 2, cityIndex);
//                            sb.append(city).append("|");
//                        }
//                        positionList.add(sb.toString());
//                    }
//
//                }
//            }
//        });
//
//        //去重
//        positionList.stream().distinct().forEach(o -> {
//            String[] split = o.split("\\|");
//            if (split.length > 4) {
//                Company company = new Company();
//                company.setGroupId(split[0]);
//                company.setRegion(split[1]);
//                company.setServNumber(split[2]);
//                company.setAttrValue1(split[3]);
//                company.setCity(split[4]);
//                queue.offer(company);
//            }
//        });


        String errFile = saveFile.replaceAll(".log", "_err.log");
        if (FileUtil.exist(errFile)) {
            List<String> errList = FileUtil.readUtf8Lines(errFile);
            if (errList.size() > 0) {
                for (String errCom : errList) {
                    Company company = JSON.parseObject(errCom, Company.class);
                    queue.offer(company);
                }
            }
            FileUtil.del(errFile);
        }

        DataQueue allCompay = new DataQueue();
        allCompay.setQueue(queue);
        return allCompay;
    }


    private static void taskBegin(DataQueue allEnpQueue, String saveFile, int threadCount) {
        ThreadGetLocation threadGetLocation = new ThreadGetLocation();
        threadGetLocation.setDataQueue(allEnpQueue);
        threadGetLocation.setDesPath(saveFile);
        for (int i = 0; i < threadCount; i++) {
            new Thread(threadGetLocation).start();
        }
    }

}
